<?php
/**
 * 路径修复版本的 base.php
 * 自动检测并加载正确路径的依赖文件
 */

// 定义可能的路径组合
$possiblePaths = [
    // 相对于 /api/miniapp/ 的路径
    ['../../utils/Database.php', '../../config/database.php'],
    ['../../../utils/Database.php', '../../../config/database.php'],
    ['../../backend/utils/Database.php', '../../backend/config/database.php'],
    ['../../../backend/utils/Database.php', '../../../backend/config/database.php'],
    // 绝对路径（如果需要）
    [dirname(__DIR__, 3) . '/utils/Database.php', dirname(__DIR__, 3) . '/config/database.php'],
    [dirname(__DIR__, 2) . '/utils/Database.php', dirname(__DIR__, 2) . '/config/database.php'],
];

$loaded = false;
foreach ($possiblePaths as $paths) {
    if (file_exists($paths[0]) && file_exists($paths[1])) {
        require_once $paths[0];
        require_once $paths[1];
        $loaded = true;
        break;
    }
}

if (!$loaded) {
    die('Error: Unable to locate required files (Database.php and database.php)');
}

class MiniappBase {
    protected $db;
    protected $wxAppId;
    protected $wxSecret;
    
    public function __construct() {
        $this->db = new Database();
        $this->wxAppId = WX_APPID;
        $this->wxSecret = WX_SECRET;
    }
    
    /**
     * 统一API响应格式
     */
    public function success($data = null, $message = '操作成功') {
        $this->jsonResponse([
            'code' => 200,
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ]);
    }
    
    public function error($message = '操作失败', $code = 400, $data = null) {
        $this->jsonResponse([
            'code' => $code,
            'success' => false,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ]);
    }
    
    private function jsonResponse($data) {
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit;
        }
        
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    /**
     * 获取微信用户信息
     */
    protected function getWxUserInfo($code) {
        // 换取access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        $params = [
            'appid' => $this->wxAppId,
            'secret' => $this->wxSecret,
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        
        $response = $this->httpGet($url . '?' . http_build_query($params));
        return json_decode($response, true);
    }
    
    /**
     * 验证用户token
     */
    protected function verifyToken($token) {
        if (empty($token)) {
            return false;
        }
        
        // 移除Bearer前缀
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }
        
        try {
            // 简单的token验证，实际项目中应该使用JWT
            $sql = "SELECT * FROM users WHERE token = ? AND token_expires > NOW()";
            $user = $this->db->fetchOne($sql, [$token]);
            return $user;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取当前用户
     */
    protected function getCurrentUser() {
        $token = $this->getAuthToken();
        if (!$token) {
            $this->error('需要登录', 401);
        }
        
        $user = $this->verifyToken($token);
        if (!$user) {
            $this->error('登录已过期', 401);
        }
        
        return $user;
    }
    
    /**
     * 获取Authorization token
     */
    private function getAuthToken() {
        $headers = getallheaders();
        $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
        
        if (strpos($authHeader, 'Bearer ') === 0) {
            return substr($authHeader, 7);
        }
        
        return $_GET['token'] ?? $_POST['token'] ?? '';
    }
    
    /**
     * HTTP GET请求
     */
    private function httpGet($url) {
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'timeout' => 10
            ]
        ]);
        
        return file_get_contents($url, false, $context);
    }
    
    /**
     * 生成随机token
     */
    protected function generateToken($userId) {
        return md5($userId . time() . rand(1000, 9999));
    }
    
    /**
     * 分页处理
     */
    protected function paginate($page = 1, $limit = 20) {
        $page = max(1, intval($page));
        $limit = min(100, max(1, intval($limit))); // 限制最大100条
        $offset = ($page - 1) * $limit;
        
        return [
            'page' => $page,
            'limit' => $limit,
            'offset' => $offset
        ];
    }
    
    /**
     * 格式化时间
     */
    protected function formatTime($datetime) {
        if (empty($datetime)) return null;
        return date('Y-m-d H:i:s', strtotime($datetime));
    }
    
    /**
     * 记录API日志
     */
    protected function logApi($action, $data = []) {
        $logData = [
            'action' => $action,
            'method' => $_SERVER['REQUEST_METHOD'],
            'uri' => $_SERVER['REQUEST_URI'],
            'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'data' => json_encode($data),
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        try {
            $sql = "INSERT INTO api_logs (action, method, uri, ip, user_agent, data, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
            $this->db->execute($sql, array_values($logData));
        } catch (Exception $e) {
            // 日志记录失败不应影响主要功能
            error_log("API log failed: " . $e->getMessage());
        }
    }
}
?>